package top.tagao.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.tagao.yygh.common.exception.YyghException;
import top.tagao.yygh.common.helper.HttpRequestHelper;
import top.tagao.yygh.common.rabbit.constant.MqConst;
import top.tagao.yygh.common.rabbit.service.RabbitService;
import top.tagao.yygh.common.result.ResultCodeEnum;
import top.tagao.yygh.enums.OrderStatusEnum;
import top.tagao.yygh.enums.PaymentTypeEnum;
import top.tagao.yygh.enums.RefundStatusEnum;
import top.tagao.yygh.hosp.client.HospitalFeignClient;
import top.tagao.yygh.model.order.OrderInfo;
import top.tagao.yygh.model.order.PaymentInfo;
import top.tagao.yygh.model.user.Patient;
import top.tagao.yygh.order.mapper.OrderMapper;
import top.tagao.yygh.order.service.OrderService;
import top.tagao.yygh.order.service.WeixinService;
import top.tagao.yygh.user.client.PatientFeignClient;
import top.tagao.yygh.vo.hosp.ScheduleOrderVo;
import top.tagao.yygh.vo.msm.MsmVo;
import top.tagao.yygh.vo.order.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/14 9:40
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;


    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WeixinService weixinService;

    /**
     * @date  生成挂号订单
     * @param scheduleId
     * @param patientId
     * @return java.lang.Long 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long  saveOrder(String scheduleId, Long patientId) {
        // 1. 获取就诊人信息
        Patient patient = patientFeignClient.getPatient(patientId);

        // 2. 获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);

        // 3. 判断当前时间是否可以进行预约
        if( new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
            || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()){
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        // 4. 获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        // 5. 添加到订单编号
        OrderInfo orderInfo = new OrderInfo();
        // scheduleOrderVo 数据复制到 orderInfo
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);

        // 6. 设置orderInfo 其他属性
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

        // 7. 添加订单信息进入数据库
        baseMapper.insert(orderInfo);

        // 8. 调用医院接口,实现预约挂号操作
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        System.out.println(signInfoVo.getSignKey() + "---------");
        paramMap.put("sign", sign);
        System.out.println(sign);
        // 9. 请求医院系统接口,
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");

        if(result.getInteger("code")==200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;

            // 10. 在(9.)取出数据 更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);

            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");



            //短信实体
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate =  new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            param.put("amount", orderInfo.getAmount());
            param.put("reserveDate", reserveDate);
            param.put("name", orderInfo.getPatientName());
            param.put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            msmVo.setParam(param);
            msmVo.setTemplateCode("SMS_236985026");
            //发送信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setMsmVo(msmVo);

            // 消息生产者,往RabbitMQ发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();

    }

    /**
     * @date  根据订单id查询订单详情
     * @param orderId
     * @return top.tagao.yygh.model.order.OrderInfo
     */
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
         this.packOrderInfo(orderInfo);
        return orderInfo;
    }

    /**
     * @date  订单列表（条件查询带分页）
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //OrderQueryVo获取条件值
        String name = orderQueryVo.getKeyword();
        Long patientId = orderQueryVo.getPatientId();
        String orderStatus = orderQueryVo.getOrderStatus();
        String reserveDate = orderQueryVo.getReserveDate();
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;

    }

    /**
     * @date  订单详情
     * @param id
     */
    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.getById(id);
        this.packOrderInfo(orderInfo);
        map.put("orderInfo",orderInfo);
        Patient patient
                =  patientFeignClient.getPatient(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    /**
     * @date  取消预约
     * @param orderId
     * @return java.lang.Boolean
     */
    @Override
    public Boolean cancelOrder(Long orderId) {
        // 1. 获取订单消息
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        // 2. 判断是否在退号时间内
        DateTime dateTime = new DateTime(orderInfo.getQuitTime());
        System.out.println(dateTime);
        //if (dateTime.isBeforeNow()) {
        //    throw  new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        //}
        // 3. 调用医院接口实现取消预约
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (signInfoVo == null) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("hoscode",orderInfo.getHoscode());
        requestMap.put("hosRecordId",orderInfo.getHosRecordId());
        requestMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(requestMap, signInfoVo.getSignKey());
        requestMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(requestMap,
                signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        // 4. 根据医院接口返回数据
        if(result.getInteger("code")!=200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());

        }

        // 5. 根据 yygh_order.order_info的status (已支付) 判断当前订单是否可以取消
        if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
            // 6. 调用微信接口,实现退款
            Boolean isRefund = weixinService.refund(orderId);
            if(!isRefund) {
                throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
            }
        }

        // 7. 更新订单状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);


        // 8. 短信模板
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("reserveDate",reserveDate);
        param.put("name", orderInfo.getPatientName());
        param.put("title",orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
        msmVo.setParam(param);
        msmVo.setTemplateCode("SMS_236875200");

        // 9. RabbitMQ的内容参数
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        orderMqVo.setMsmVo(msmVo);

        // 10. RabbitMQ发送
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        return true;

    }


    /**
     * @date  就医提醒
     */
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfoList) {
            // 短信提醒模板
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_236815226");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            param.put("reserveDate", reserveDate);
            param.put("name", orderInfo.getPatientName());
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    /**
     * @date  订单统计
     * @param orderCountQueryVo 
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        Map<String, Object> map = new HashMap<>();

        List<OrderCountVo> orderCountVoList  = baseMapper.selectOrderCount(orderCountQueryVo);
        //日期列表
        List<String> dateList =orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer>  countList = orderCountVoList.stream().map(OrderCountVo :: getCount ).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }

    /**
     * @date  封装订单状态  int -> String
     * @param orderInfo
     */
    private void packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()) );
    }


}
